package com.lagou.serializer;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;

    private Serializer serializer;

    private static final int headSize = 4;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> list) throws Exception {
        int readAble = in.readableBytes();
        if (readAble < headSize) {
            System.out.println("byte buf 小于 4");
            return;
        }
        in.markReaderIndex();
        int size = in.readInt();
        if (readAble < (size + headSize)) {
            in.resetReaderIndex();
            return;
        }

        byte[] bytes = new byte[size];
        in.readBytes(bytes);
        Object o = serializer.ByteToObject(clazz, bytes);
        list.add(o);
    }
}
